/*
 * @Author: 悦者生存 1002783067@qq.com
 * @Date: 2023-11-05 10:01:37
 * @LastEditors: 悦者生存 1002783067@qq.com
 * @LastEditTime: 2024-04-30 16:27:03
 * @FilePath: /login-template/client/src/pages/login.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import LoginImage from '@/assets/login.jpeg';
import LogoImage from '@/assets/logo.jpeg';
import { login, register } from '@/services/user';
import { SALT } from '@/utils/constants';
import { toHome } from '@/utils/router';
import {
  MD5,
  getValidateCode,
  validateConfirmPassword,
  validatePassword,
} from '@/utils/utils';
import {
  LockOutlined,
  SafetyCertificateOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { Button, Col, Form, Input, Row, Tabs, message } from 'antd';
import { useCallback, useState } from 'react';
import Captcha from 'react-captcha-code';
import { connect } from 'umi';

import styles from './index.less';

const tabs = [
  {
    label: '登录',
    key: 'login',
  },
  {
    label: '注册',
    key: 'register',
  },
];

interface Props {
  dispatch: (params: any) => void;
}

function Login(props: Props) {
  const { dispatch } = props;
  // form
  const [form] = Form.useForm();
  // state
  const [activeKey, setActiveKey] = useState('login');
  const [code, setCode] = useState(getValidateCode());

  const onFinish = async (values: any) => {
    if (values['captcha'] !== code) {
      message.error('验证码输入错误，请重新输入');
      form.setFieldValue('captcha', '');
      return;
    }
    // 把盐上传到服务器
    if (activeKey === 'register') {
      values['password'] = await MD5(values['password'], SALT);
      // 请求接口的时候去掉confirmPassword
      delete values['confirmPassword'];
      try {
        let data = await register(values);
        if (data === 'ok') {
          setActiveKey('login');
          form.resetFields();
          // 登录成功以后刷新验证码
          handleClick();
        }
      } catch (e: any) {
        message.error(e);
      }

      // 注册好了以后设置为空
    } else {
      values.password = await MD5(values.password, SALT);
      const result = await login(values);
      if (result?.token) {
        // 存档当前对象
        dispatch({
          type: 'user/setCurrentUser',
          payload: result,
        });
        localStorage.setItem('jwt_token', result.token);
        toHome();
      }
    }
  };

  const handleClick = useCallback(() => {
    let code = getValidateCode();
    setCode(code);
  }, []);

  const onChangeTab = (activeKey: string) => {
    form.resetFields();
    setActiveKey(activeKey);
  };

  return (
    <div className={styles.loginContainer}>
      <Row className={styles.background}>
        <Col span={0} lg={12} xl={12} className={styles.leftSection}>
          <img src={LoginImage} className={styles.backgroundImage} />
        </Col>
        <Col span={24} lg={12} xl={12} className={styles.rightSection}>
          <div className={styles.loginSection}>
            <div className={styles.logo}>
              <img src={LogoImage} className={styles.logoImage} />
            </div>
            <Tabs
              defaultActiveKey="1"
              centered
              items={tabs}
              onChange={onChangeTab}
              activeKey={activeKey}
            />
            <Form
              form={form}
              name="basic"
              style={{ width: 300 }}
              initialValues={{ remember: true }}
              onFinish={onFinish}
              autoComplete="off"
            >
              <Form.Item
                name="username"
                validateTrigger={['onBlur']}
                rules={[{ required: true, message: '请输入你的用户名!' }]}
              >
                <Input placeholder="用户名" prefix={<UserOutlined />} />
              </Form.Item>
              <Form.Item
                name="password"
                validateTrigger={['onBlur']}
                rules={[
                  {
                    validator: (rule, value) => validatePassword(rule, value),
                  },
                ]}
              >
                <Input.Password
                  type="password"
                  placeholder="密码"
                  prefix={<LockOutlined />}
                />
              </Form.Item>
              {activeKey === 'register' && (
                <Form.Item
                  name="confirmPassword"
                  validateTrigger={['onBlur']}
                  rules={[
                    ({ getFieldValue }) => ({
                      validator(rule, value) {
                        return validateConfirmPassword(
                          rule,
                          value,
                          getFieldValue,
                        );
                      },
                    }),
                  ]}
                >
                  <Input.Password
                    placeholder="请再次输入密码"
                    prefix={<LockOutlined />}
                  />
                </Form.Item>
              )}
              {/* <Form.Item>
          <Form.Item name="remember" valuePropName="checked" noStyle>
            <Checkbox>Remember me</Checkbox>
          </Form.Item>

          <a className="login-form-forgot" href="">
            Forgot password
          </a>
        </Form.Item> */}
              <Form.Item>
                <Row gutter={16}>
                  <Col span={16}>
                    <Form.Item
                      validateTrigger={['onBlur']}
                      name="captcha"
                      rules={[{ required: true, message: '请输入验证码!' }]}
                    >
                      <Input
                        placeholder="请输入验证码"
                        prefix={
                          <SafetyCertificateOutlined className="site-form-item-icon" />
                        }
                      />
                    </Form.Item>
                  </Col>
                  <Col span={8}>
                    <Captcha
                      onClick={handleClick}
                      code={code}
                      height={32}
                      width={90}
                    />
                  </Col>
                </Row>
              </Form.Item>
              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  style={{ width: '100%' }}
                >
                  {activeKey === 'login' ? '登录' : '注册'}
                </Button>
              </Form.Item>
            </Form>
          </div>
        </Col>
      </Row>
    </div>
  );
}

export default connect()(Login);
